package Demo1;

import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-08-17
 * Time: 10:24
 */
public class Test {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {

        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val; this.next = next;
        }
    }
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode slow = head;
        ListNode fast = head;

        //让快指针先走n步
        while(n != 0){
            fast = fast.next;
            n--;
        }

        //快慢指针一起走
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }

        //头删
        if(fast == null){
            head = head.next;
            return head;
        }

        //修改slow.next指向
        slow.next = slow.next.next;
        return head;
    }
    //定义变量，用来判段是否要进一
    public boolean ret = false;
    public ListNode head = null;
    public ListNode cur = head;

    public void addlast(int value){
        if(ret) value += 1;
        ListNode newNode = null;

        if(value >= 10){
            newNode = new ListNode(value - 10);
            ret = true;
        }else{
            newNode = new ListNode(value);
            ret = false;
        }

        //尾插节点
        if(head == null){
            head = cur = newNode;
        }else{
            cur.next = newNode;
            cur = newNode;
        }
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode cur1 = l1;
        ListNode cur2 = l2;

        //遍历链表相加
        while(cur1 != null && cur2 != null){
            int value = cur1.val + cur2.val;
            addlast(value);
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        while(cur1 != null){
            int value = cur1.val;
            addlast(value);
            cur1 = cur1.next;
        }
        while(cur2 != null){
            int value = cur2.val;
            addlast(value);
            cur2 = cur2.next;
        }

        if(cur1 == null && cur2 == null && ret == true){
            ListNode newNode = new ListNode(1);
            cur.next = newNode;
        }
        return head;
    }
}
